#include "MCU_include.h"


_Time_Flag		Time_Flag;
_Time_State		Time_State;
vu8		nCnt = 0;


//volatile bit	B_FLAG_PowerStable1 = 0, B_FLAG_PowerStable2 = 0,B_FLAG_PotDet2 ;
volatile bit B_FLAG_PotDet;
volatile u8		PowerStableCnt = 0, PotDetTimes = 0;



//************Power measurement interval of 0.5s**************//
void TB0_Init()
{
	_pscr = 0x02;			//TB0 clock source selected as fSUB
	_tb0c = 0b00000011;		//TB0ON	─	─	─	─	TB02	TB01	TB00,0.0625S over flow
	TB0_ON();
}

void CTM_Init()
{
	CTM0_Init();
	CTM1_Init();
	CTM2_Init();
	PTM_Init();	
}


//**********1ms*************//
void CTM0_Init()
{
	_ctm0c0 = 0b00100000;		//fclk=fH/16=1MHz,1/fclk=1us,
	_ctm0c1 = 0b11000001;		
	_ctm0al = 125 & 0x0ff;		//125*1us
	_ctm0ah = 125>>8;			//
	CTM0_ON();
}


//***********************//
void CTM1_Init()
{
	_ctm1c0 = 0b00100000;		//fclk=fH/16=1MHz,1/fclk=1us,
	_ctm1c1 = 0b11000001;		
	_ctm1al = 100 & 0x0ff;		//100us
	_ctm1ah = 100 >> 8;			//100us overflow		
}


//***********************//
void CTM2_Init()
{
	_ctm2c0 = 0b00100000;		//fclk=fH/16=1MHz,1/fclk=1us,	
	_ctm2c1 = 0b11000001;		
	_ctm2al = 1000 & 0x0ff;	//1000*1us=1ms
	_ctm2ah = 1000>>8;		//
}

void PTM_Init()
{
	_ptmc0 = 0b00100000;
	_ptmc1 = 0b11000001;
	_ptmal = 1000 & 0x00ff;		
	_ptmah = 1000 >> 8;
}


//************** ****************//
void Time_Base()
{
	if(1 == Time_Flag.Fg_1ms)
	{
		Time_Flag.Fg_1ms = 0;				
		check_pot_num++;
		if(++Time_State.Time_1ms >= 10)
		{
			Time_State.Time_1ms = 0;
			Time_Flag.Fg_10ms = 1;					//10ms
			
			if(++Time_State.Time_10ms >= 10)		
			{
				Time_State.Time_10ms = 0;
				Time_Flag.Fg_100ms = 1;			//100ms
				
				if (_pwmon)
				{
				if (B_FLAG_PotDet == 0)
					{
					if (++PotDetTimes >= 5)		//
						{
							PotDetTimes = 0;
							B_FLAG_PotDet = 1;
							
						}
					}										
				}
					if(FG_IH_Status.flagBit.PWM_ON_OFF)
					{
							FLAG.flagBit.PowerONFlag =1;
					}
					else
					{
							FLAG.flagBit.PowerONFlag=0;
					}	
				
				if(++Time_State.Time_100ms >= 10)
				{
					Time_State.Time_100ms = 0;
					Time_Flag.Fg_1s = 1;			//1s
					
					
					if(++Time_State.Time_1s >= 60)
					{
						Time_State.Time_1s = 0;
						Time_Flag.Fg_1min = 1;		//1min
					
						if(++Time_State.Time_1min >= 60)
						{
							Time_State.Time_1min = 0;
							Time_Flag.Fg_1h = 1;	//1h
							
							Time_State.Time_1h++;
						}
					}
				}
			}
		}
	}
}





//**************************************//
void __attribute((interrupt(0x34))) CTM0_ISR(void)	//1ms
{
 	_ctm0af = 0;
 	_mf2f = 0;
 	if (++nCnt >= 8 )	//	8*125us = 1ms
 	{
	 	nCnt = 0;
	 	Time_Flag.Fg_1ms = 1;
	 	if (OVP2_Cnt != 0)
	 	{
	 		if (++OVP2_TimeCnt >= 10)
	 		{
	 			OVP2_TimeCnt = 0;
	 			OVP2_ClrFlag =1;
	 		}
	 	}
 	}
 		
}

